package com.alex;

import static com.anythink.core.api.ATInitMediation.getStringFromMap;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.interstitial.unitgroup.api.CustomInterstitialAdapter;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;

import java.util.Map;

public class AlexGromoreInterstitialAdapter extends CustomInterstitialAdapter {

    boolean isC2SBidding = false;
    String slotId;
    AlexGromoreConfig mATConfig;
    private Map<String, Object> mNetworkMap;
    private TTFullScreenVideoAd mTTFullScreenVideoAd; // 插全屏广告对象

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra,
                                    Map<String, Object> localExtra) {
        if (!(context instanceof Activity)) {
            notifyATLoadFail("", "Gromore: context must be activity");
            return;
        }
        if (!initAndVerifyRequestParams(context, serverExtra, localExtra)) {
            notifyATLoadFail("", "app_id or slot_id is empty!");
            return;
        }

        AlexGromoreInitManager.getInstance()
                .initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        //start load iv
                        AdSlot.Builder adSlotBuilder = new AdSlot.Builder().setCodeId(slotId)
                                .setImageAcceptedSize(mATConfig.mWidth, mATConfig.mHeight)
                                //.setOrientation(mATConfig.mOrientation)//
                                .setMediationAdSlot(new MediationAdSlot.Builder()
                                        .setMuted(mATConfig.adSound == 0)//是否静音
                                        .build());

                        if (!TextUtils.isEmpty(mATConfig.mUserId)) {
                            adSlotBuilder.setUserID(mATConfig.mUserId);
                        }
                        if (!TextUtils.isEmpty(mATConfig.mUserData)) {
                            adSlotBuilder.setUserData(mATConfig.mUserData);
                        }

                        AdSlot adSlot = adSlotBuilder.build();

                        TTAdNative adNativeLoader = TTAdSdk.getAdManager()
                                .createAdNative((Activity) context);//必须传入Activity才会有加载回调

                        adNativeLoader.loadFullScreenVideoAd(adSlot,
                                new TTAdNative.FullScreenVideoAdListener() {
                                    public void onError(int code, String message) {
                                        notifyATLoadFail("" + code, message);
                                    }

                                    public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                                    }

                                    public void onFullScreenVideoCached() {
                                    }

                                    public void onFullScreenVideoCached(TTFullScreenVideoAd ad) {
                                        mTTFullScreenVideoAd = ad;
                                        if (isC2SBidding) {
                                            runOnNetworkRequestThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    double price = 0;
                                                    price = AlexGromoreUtil.getBestPriceInCacheNew(mTTFullScreenVideoAd);

                                                    mBiddingListener.onC2SBiddingResultWithCache(
                                                            ATBiddingResult.success(price,
                                                                    System.currentTimeMillis() + "",
                                                                    null, mATConfig.mCurrency),
                                                            null);
                                                }
                                            });
                                        } else {
                                            if (mLoadListener != null) {
                                                mLoadListener.onAdCacheLoaded();
                                            }
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        notifyATLoadFail("", errorMsg);
                    }
                });

    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra,
                                       Map<String, Object> localExtra,
                                       ATBiddingListener biddingListener) {
        isC2SBidding = true;
        loadCustomNetworkAd(context, serverExtra, localExtra);
        return true;
    }


    @Override
    public void show(Activity activity) {
        if (isAdReady()) {
            this.mTTFullScreenVideoAd.setFullScreenVideoAdInteractionListener(
                    new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
                        public void onAdShow() {
                            mNetworkMap = AlexGromoreConst.getNetworkMap(mTTFullScreenVideoAd);
                            if (mImpressListener != null) {
                                mImpressListener.onInterstitialAdShow();
                            }
                        }

                        public void onAdVideoBarClick() {
                            if (mImpressListener != null) {
                                mImpressListener.onInterstitialAdClicked();
                            }
                        }

                        public void onAdClose() {
                            if (mImpressListener != null) {
                                mImpressListener.onInterstitialAdClose();
                            }
                        }

                        public void onVideoComplete() {
                            if (mImpressListener != null) {
                                mImpressListener.onInterstitialAdVideoEnd();
                            }
                        }

                        public void onSkippedVideo() {
                        }
                    });
            this.mTTFullScreenVideoAd.showFullScreenVideoAd(activity);
        }
    }

    private boolean initAndVerifyRequestParams(Context context, Map<String, Object> serverExtra,
                                               Map<String, Object> localExtra) {
        String appId = getStringFromMap(serverExtra, "app_id");
        slotId = getStringFromMap(serverExtra, "slot_id");

        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(slotId)) {
            return false;
        }
        mATConfig = new AlexGromoreConfig(context, serverExtra);
        mATConfig.parseInterstitialLocalData(localExtra);

        return true;
    }

    @Override
    public void destory() {
        if (mTTFullScreenVideoAd != null && mTTFullScreenVideoAd.getMediationManager() != null) {
            mTTFullScreenVideoAd.getMediationManager().destroy();
        }
    }


    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return AlexGromoreInitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return AlexGromoreInitManager.getInstance().getNetworkName();
    }

    @Override
    public boolean isAdReady() {
        return mTTFullScreenVideoAd != null && mTTFullScreenVideoAd.getMediationManager().isReady();
    }

    @Override
    public Map<String, Object> getNetworkInfoMap() {
        return mNetworkMap;
    }
}
